import React, { Component } from 'react';
import { findFilmsPage } from '@/api/MaiZuo';
import BetterScroll from 'better-scroll';

import './css/index.css';

export default class App extends Component {
  state = {
    count: 0,
    list: [],
  };
  constructor() {
    super();
    console.log('constructor');
  }

  componentDidMount() {
    console.log('componentDidMount');
    this.getList();
  }

  getList(pageNum = 1, pageSize = 10) {
    findFilmsPage(pageNum, pageSize).then((res) => {
      console.log('films', res);

      this.setState({
        list: res.films,
      });
    });
  }

  render() {
    console.log('render');
    return (
      <div>
        <h1>App</h1>
        <button onClick={() => this.setState({ count: 1 })}>click1</button>
        <div id='count'>{this.state.count}</div>
        <button onClick={() => this.getList(2)}>click2</button>
        <div id='wrapper'>
          <ul className='cinemaList'>
            {this.state.list.map((item) => {
              return (
                <li key={item.filmId}>
                  <div className='cinemaName'>{item.name}</div>
                </li>
              );
            })}
          </ul>
        </div>
      </div>
    );
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (
      JSON.stringify(nextProps) !== JSON.stringify(this.props) ||
      JSON.stringify(nextState) !== JSON.stringify(this.state)
    ) {
      console.log('shouldComponentUpdate 放行更新');
      return true; // 放行更新
    }
    return false; // 阻止更新
  }

  /**
   * 16.2 之后的版本生命周期发生更改，此方法不推荐使用了
   * 不想出现警告，修改为 UNSAFE_componentWillUpdate
   */
  componentWillUpdate(nextPrevProps, nextPrevState) {
    console.log('componentWillUpdate', document.querySelector('#count'));
    console.log('componentWillUpdate', nextPrevProps, nextPrevState);
  }

  componentDidUpdate(prePrevProps, prePrevState) {
    console.log('componentDidUpdate', document.querySelector('#wrapper'));
    console.log('componentDidUpdate', prePrevProps, prePrevState);
    // 更新完dom后，获取dom 进行初始化操作
    prePrevState.list.length === 0 && new BetterScroll('#wrapper');
  }
}
